const moment = require("moment")//格式化时间的中间件
const { login, regist } = require("../model/usersModel");
//引入jsonwebtoken 令牌
const jwt = require('jsonwebtoken');
//登入
const loginCtr = async (req, res) => {
    let { password, username } = req.body
    //防止前端没有传递信息
    if (!username && !password) {
        res.send({ code: 0, status: false, msg: "没有传递数据" })
        return
    }
    let info = { password: password, username: username }
    let result = await login(info)
    console.log(result)
    if (!result.length) {
        res.send({ code: 0, status: false, msg: "用户名或者密码错误" })
    } else {
        let { username, nickname, uid } = result[0]
        let data = {
            username: username,
            nickname: nickname,
            uid: uid
        }

        //生成token
        //自定义一个加密字符串
        let sercrect = "MY_NAME_IS_LILEI"
        let token = jwt.sign(data, sercrect, {
            expiresIn: 60 * 5
        })//1.payload 2.sercrect 3,{expiresIn:xx,algorithm:'rs256'}

        res.send({ code: 1, status: true, data: data, msg: "登入成功", token: token })
    }
}

//注册
const registCtr = async (req, res) => {
    // 处理生成uid 生成一个8位的用户id
    const str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    const arr = [];
    for (var i = 0; i < 8; i++) {
        const index = parseInt(Math.random() * str.length)
        arr.push(str[index])
    }
    //添加一个随机生成的uid到body
    req.body.uid = arr.join("")
    //创建时间
    const time = moment().format("YYYY/MM/DD,hh:mm:ss:ms")
    req.body.createTime = time
    //注册之前先查找数据库 判断用户名是否重复
    let veriUsername = await login({ username: req.body.username })
    if (veriUsername.length) {
        //表示用户名重复
        res.send({ code: 1, status: false, msg: "用户名重复" })
        return
    }
    //调用注册的方法
    let result = await regist(req.body)
    if (result) {
        res.send({ code: 1, status: true, msg: "注册成功" })
    } else {
        res.send({ code: 0, status: false, msg: "注册成功" })
    }
}

module.exports = {
    loginCtr,
    registCtr
}